import userTempId from "@/utils/userTempId";
import { reqLoginUser, reqLogout, reqUserInfo } from "@/api";

const state = {
    userTempId: userTempId(), // 用户临时id
    token: localStorage.getItem("token_key") || "", // 用户token
    userInfo: {}, // 用户信息
};

const mutations = {
    // 保存token
    RECEIVE_TOKEN(state, { token }) {
        state.token = token;
    },
    // 保存用户信息
    RECEIVE_USER_INFO(state, { userInfo }) {
        state.userInfo = userInfo;
    },
    // 重置用户信息
    RESET_USER_INFO(state) {
        state.userInfo = {};
        state.token = "";
        localStorage.removeItem("token_key");
    },
};

const actions = {
    // 获取用户token
    async getUserToken({ commit }, userInfo) {
        const result = await reqLoginUser(userInfo);
        const token = result.token;
        localStorage.setItem("token_key", token);
        commit("RECEIVE_TOKEN", { token });
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        const userInfo = await reqUserInfo();
        commit("RECEIVE_USER_INFO", { userInfo });
    },
    // 重置用户信息
    resetUserInfo({ commit }) {
        commit("RESET_USER_INFO");
    },
    // 退出登录
    async getLogout({ commit }) {
        await reqLogout();
        commit("RESET_USER_INFO");
    },
};
export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
